<template>
  <el-container id="collection" v-if="isloaded">
    <el-header class="toolbar1" style="height: 54px;">
      <el-row>
        <el-button icon="el-icon-arrow-left" @click="handleGoBack" class="back">上一级</el-button>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="tit">
          <el-breadcrumb-item><i @click="getCollection" :class="addressList.length == 0 ? 'current':''">{{addressPrompt}}</i></el-breadcrumb-item>
                  <template v-for="(item,index) in addressList">
                    <el-breadcrumb-item :key='index'   ><i @click="getData(item.id,true)" :class="addressList.length == (index+1) ? 'current':''">{{item.name}}</i></el-breadcrumb-item>
                  </template>
</el-breadcrumb>
      </el-row>
      <el-row>
          <el-button-group>
              <el-button
                      plain
                      @click="listVisibleFun(1)"
                      :class="!listVisible ? 'focus' : ''">
                  <i class="fa fa-bars"></i>
              </el-button>
              <el-button
                      plain
                      @click="listVisibleFun(0)"
                      :class="listVisible? 'focus' : ''"
                      icon="el-icon-menu">
              </el-button>
          </el-button-group>
        <!--<el-button class="list" icon="fa fa-list-ul" v-bind:class="{ activeList: !listVisible }" @click="listVisibleFun(1)" plain></el-button>-->
        <!--<el-button class="menu" icon="el-icon-menu" plain v-bind:class="{ activeList: listVisible }" @click="listVisibleFun(0)"></el-button>-->
        <el-button class="refresh" icon="el-icon-refresh" plain @click="reload"></el-button>
      </el-row>
    </el-header>
    <el-main>
      <div class="toolbar">
        <el-button  class="bt1" @click="cancelCollection"
          :disabled="flag === 1 || arrId.length == 0">
          <i class="fa fa-star" aria-hidden="true"></i> 取消所选收藏
        </el-button>
      </div>
      <el-container v-if="hasCollect">
        <div v-show="listVisible" class="big-show">
          <!-- <div class="top">
                <img src="../assets/img/file/check_normal.png" alt="" v-if="!allCheck" @click="checkAll">
                <img src="../assets/img/file/check_highlight.png" alt="" v-else @click="unCheckAll">
                <p>全选</p>
            </div> -->
            <template v-for="(item,index) in collectionList">
                <div class="bigIcon" :class='{checked:item.checked}' v-loading="listLoading" :key='index' @click="bigiconClicked(item)">
                    <span :class="'file-icon '+item.iconcls" class="icon"></span>
                    <el-tooltip
                                class="item"
                                effect="dark"
                                v-if="item.fileName && $abslength(item.fileName) > 20"
                                :content="item.fileName"
                                placement="bottom"
                        >
                            <p  @click="handleCellClick(item)">{{ item.fileName.substring(0,$getFontShowLength(item.fileName,20))+'...'}}</p>
                        </el-tooltip>
                        <p  v-else @click.stop @click="handleCellClick(item)">{{ item.fileName }}</p>
                    <img src="../assets/img/file/unchecked.png" alt="" v-show="!item.checked" class="hovershow">
                    <img src="../assets/img/file/checked.png" alt="" v-show="item.checked" class="hovershow">
                    <el-popover placement="bottom" width="90" trigger="hover">
                        <ul class="options-list settingOptions">
                            <li @click="CancleCollectFile(item)">
                                <i class="fa fa-star" aria-hidden="true" style="color: rgba(102, 102, 102, 1);"></i> 取消收藏
                            </li>
                            <li v-if="item.fileType == 0" @click="downloadFile(item)">
                                <i class="fa fa-cloud-download" aria-hidden="true"></i> 下载
                            </li>
                            <li v-if="item.fileType == 0" @click="previewFile(item)">
                                <i class="fa fa-file" aria-hidden="true"></i> 文件预览
                            </li>
                        </ul>
                        <i slot="reference" class="el-icon-more hovershow" style="cursor: pointer;position:absolute;right:0;" @click.stop></i>
                    </el-popover>
                </div>
            </template>
        </div>
        <el-table
                size="small"
                v-show="!listVisible"
                :data="collectionList"
                v-loading="listLoading"
                element-loading-text="拼命加载中"
                @selection-change="selsChange"
                style="width: 100%;font-family:'宋体'"
        >
            <el-table-column type="selection"  width="80" :selectable="selectable"></el-table-column>
            <el-table-column label="名称" prop="fileName" width="330">
                <template slot-scope="scope">
                    <div class="folder-box" @click="handleCellClick(scope.row)">
                        <span :class="'file-icon '+scope.row.iconcls"></span>
                        <el-tooltip
                                class="item"
                                effect="dark"
                                v-if="scope.row.fileName && $abslength(scope.row.fileName)>22"
                                :content="scope.row.fileName"
                                placement="top-start"
                        >
                            <span class="file-name">{{ scope.row.fileName.substring(0,$getFontShowLength(scope.row.fileName,22))+'...'}}</span>
                        </el-tooltip>
                        <span class="file-name" v-else>{{scope.row.fileName}}</span>
                        <div class="folder-box-options"
                             v-if="scope.row.fileType == 0 && flag == 1">
                             <span v-if="scope.row.fileType == 0"
                                   style="cursor: pointer; padding-right: 10px"
                                   @click.stop
                                   @click="downloadFile(scope.row)">
                                 <i class="fa fa fa-cloud-download" aria-hidden="true"></i>下载
                            </span>
                            <span v-if="scope.row.fileType == 0"
                                  style="cursor: pointer; padding-right: 10px"
                                  @click.stop
                                  @click="previewFile(scope.row)">
                                <i class="fa fa-file" aria-hidden="true"></i>
                                预览
                            </span>
                        </div>
                        <div class="folder-box-options" v-show="flag == 0">
                            <span v-if="scope.row.fileType == 0"
                                  style="cursor: pointer; padding-right: 10px"
                                  @click.stop
                                  @click="downloadFile(scope.row)">
                                 <i class="fa fa-cloud-download" aria-hidden="true"></i>下载
                            </span>
                            <span v-if="scope.row.fileType == 0"
                                  style="cursor: pointer; padding-right: 10px"
                                  @click.stop
                                  @click="previewFile(scope.row)">
                                <i class="fa fa-file" aria-hidden="true"></i>
                                预览
                            </span>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="fileSize" label="大小">
                <template slot-scope="scope">
                    <span v-if="scope.row.fileType == 1">-</span>
                    <span v-else>{{scope.row.fileSize}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="favoriteTime" label="收藏时间"></el-table-column>
            <el-table-column prop="creatTime" label="创建时间"></el-table-column>
            <el-table-column prop="updateTime" label="修改时间"></el-table-column>
            <el-table-column label="操作" width="150" v-if="flag==0">
                <template slot-scope="scope">
                <el-button
                        class="butt"
                        size="mini"
                        @click="CancleCollectFile(scope.row)"
                        type="text"
                >
                    <i class="fa fa-star" aria-hidden="true"></i>
                </el-button>
            </template>
            </el-table-column>
        </el-table>
      </el-container>
        <div v-else  v-loading="searchLoading" style="height:100%;width:100%;display: flex;margin-top:15%;align-items: center;flex-direction: column" >
            <img src="../assets/img/collect.png" alt="">
            <el-row style="font-size:18px;color:#B4B4B4;margin-top:9px;">暂无收藏</el-row>
            <el-row style="font-size:14px;color:#B4B4B4;margin-top:10px;">浏览其他版块看看吧~</el-row>
        </div>
    </el-main>
  </el-container>
</template>

<script>
import axios from "axios";
  import {mapState, mapMutations} from "vuex";
  import FilesTable from './file_details/FilesTable'
  import AddFile from './file_details/AddFile'
export default {
  name:"MyCollection",
  inject: ["reloadHome"],
  components: {FilesTable, AddFile},
  provide() {
      return {
        reloadFilesTableData: this.reloadFilesTableData
      }
    },
  data() {
    return {
      listVisible:false,
      listLoading: false,
      collectionList: [],
      addressPrompt: "我的收藏",
      addressList: [],
      addressIdList: [],
      crumbs: "",
      flag: 0,
      arrId: [],
      isloaded:true,
      hasCollect:true,
      searchLoading:false,
      allCheck:false,
    };
  },
  mounted() {
    this.getCollection();
  },
  methods: {
    reload(){
      this.isloaded=false;
      this.$nextTick(function() {
        this.isloaded = true;
      });
    },
    listVisibleFun(e) {
      this.arrId=[];
        if (e === 0) {
          this.listVisible = true;
        } else {
          this.listVisible = false;
        }
      },
      getSels(data){
        this.sels = data;
      },
    selectable() {
      if (!this.flag) {
        return true;
      } else {
        return false;
      }
    },
    unCheckAll(){
        collectionList.forEach(item=>{
          item.checked=false;
        })
        this.arrId=[];
        this.allCheck=false;
      },
      checkAll(){
        collectionList.forEach(item=>{
          item.checked=true;
          this.arrId.push(item.fileId);
        })
        this.allCheck=true;
      },
    CancleCollectFile(file) {
      this.$confirm("确定取消收藏？", "提示", {}).then(() => {
        this.$http
          .get("/favorites/clickCollection", {
            params: {
              id: file.fileId
            }
          })
          .then(res => {
            if (res.status == 200) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.getCollection();
            } else {
              this.$message.error("操作失败");
            }
          });
      });
    },
    /**
     * 预览文件
     */
    previewFile(file){
      console.log(file);
      let arr = ["png","jpg","pdf","gif","txt"];
      if (arr.indexOf(this.getType(file.fileName)) != -1) {
        if(this.$store.state.ipfsArray==0){
          this.$message.error('获取请求路径失败,请检查网络或呼叫管理员');
        }else{
          this.getBlob(this.$store.state.ipfsArray[1]+'ipfs/'+file.fileHash).then(blob => {
            this.imgurl = window.URL.createObjectURL(blob);
            console.log(this.imgurl)
            if(this.imgurl != ""){
              window.open(this.imgurl,"_blank")
            }
          });
        }
      } else if(file.suffix.toLowerCase() == "mp4" || file.suffix.toLowerCase() == "webm" || file.suffix.toLowerCase() == "ogg" ){
        let url = this.$store.state.ipfsArray[1]+'ipfs/'+file.fileHash;
        console.log(url);
        var page = window.open();
        var html=`<body style='background:black;display: flex;justify-content: center;align-items: center'>
                        <div style='width:980px;height: 480px'>
                            <video  style='width:980px;height: 480px' controls width='100%' autoplay id="playVideo">
                                <source class="source" src=${url} type="video/mp4">
                            </video>
                        </div>
                    </body>`
        page.document.write("<title>视频预览</title>"+html);
      }else if(file.suffix.toLowerCase() == "flv"){
        let url = this.$store.state.ipfsArray[1]+'ipfs/'+file.fileHash;
        console.log(url);
        let data = url;
        let data1 = "vcastr_file="+data+"&LogoText=ÊÓÆµ²¥·ÅÆ÷&BufferTime=3&IsAutoPlay=1";
        let data2 = "vcastr_file="+data+"&LogoText=ÊÓÆµ²¥·ÅÆ÷&IsAutoPlay=1";
        var page = window.open();
        var html=`<body style='background:black;display: flex;justify-content: center;align-items: center'>
                        <div style="width: 100%;height:100%;display: flex;justify-content: center;align-items: center;background: black">
                            <object class id="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase=${data} width="980" height="480" style="border: 1px solid #549de8">
                                <param name="movie" value="/static/flvplayer.swf">
                                <param name="quality" value="high">
                                <param name="allowFullScreen" value="true">
                                <param name="FlashVars" value=${data1}>
                                <embed src="/static/flvplayer.swf" allowfullscreen="true" flashvars=${data2} quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="980" height="480"></embed>
                            </object>
                        </div>
                    </body>`
        page.document.write("<title>视频预览</title>"+html);
        // let routeUrl = this.$router.resolve({
        //   path: "/videoPlay",
        //   query: {url:url}
        // });
        // window.open(routeUrl.href, '_blank');
      }else{
        this.$message("当前文件不支持预览，请下载查看");
      }
    },
    getType(file) {
      console.log(file);
      var filename = file;
      var index1 = filename.lastIndexOf(".");
      var index2 = filename.length;
      var type = filename.substring(index1 + 1, index2);
      console.log(type);
      return type;
    },
    downloadFile(file) {
      console.log(file);
      this.downloading=true;
      if(this.$store.state.ipfsArray[1]==0){
        this.$message.error('获取请求路径失败,请检查网络或呼叫管理员');
      }else{
        console.log(this.$store.state.ipfsArray[1]+'ipfs/'+file.fileHash)
        this.getBlob(this.$store.state.ipfsArray[1]+'ipfs/'+file.fileHash).then(blob => {
          this.downloading=false;
          this.saveAs(blob, file.fileName);
        });
      }
    },
    getBlob(url) {
      return new Promise(resolve => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };
        xhr.send();
      });
    },
    saveAs(blob, filename) {
      this.downloading=false;
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        const link = document.createElement("a");
        const body = document.querySelector("body");
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    },
    handleGoBack() {
      console.log(this.addressIdList);
      let id = this.addressIdList.pop();
      this.addressList.pop();
      // this.addressPrompt = "我的收藏/" + this.addressList.join("/");
      if (id == undefined) {
        this.$message("已经是最外层喽");
        return;
      }
      if(this.addressList.length==0){
        this.getCollection();
        this.flag = 0;
      }else if (id == 0) {
        this.getCollection();
        this.flag = 0;
      } else if (id != 0) {
        this.getData(id);
      }
    },
    handleCellClick(row) {
      console.log("cellrow:", row);
      if (row.fileType == 1) {
        this.flag = 1;
        this.addressList.push({
            name:row.fileName,
            id:row.fileId
        });
        if (row.dirId == undefined) {
          this.addressIdList.push(0);
        } else {
          this.addressIdList.push(row.dirId);
        }
        console.log(this.addressIdList);
        this.getData(row.fileId);
      } else {
        this.previewFile(row);
      }
    },
    getData(id,isclick) {
      console.log(this.addressList)
      if(isclick == true){
        this.addressList.forEach((val,key)=>{
          if(val.id == id){
            this.addressList.splice(key+1);
          }
        })
      }
      this.arrId = [];
      this.collectionList = [];
      this.listLoading = true;
      this.$http.post("/file/clickdir", { id: id }).then(res => {
        let { data, status } = res;
        console.log(data);
        if(data!=false){
          this.hasCollect = true;
          this.searchLoading = false;
        }else{
          this.searchLoading = true;
          this.hasCollect = false;

        }
        if (status === 200 && data !== null) {
          // this.addressPrompt = "我的收藏/" + this.addressList.join("/");
          data.forEach((v, k) => {
            if (v.fileName == null) v.fileName = "未命名文件夹";
            let suffixTemp = v.fileName.split('.');
                let file_icon;
                if (suffixTemp.length > 1) {
                  suffixTemp = suffixTemp[suffixTemp.length - 1];
                  file_icon = 'icon_list_' + suffixTemp
                } else if (v.fileType == 0) {
                  suffixTemp = ''
                } else {
                  suffixTemp = null
                }
            let time = v.creatTime == null ? "-" : v.creatTime;
            this.collectionList.push({
              fileId: v.id,
              dirId: v.dirId,
              fileName: v.fileName,
              fileSize:
                v.fileSize == null ? "-" : this.$getFileSize(v.fileSize),
              creatTime: time,
              suffix: suffixTemp,
              fileType: v.fileType,
              fileHash: v.fileHash,
              favoriteTime: v.updateTime == null ? time : v.updateTime,
              updateTime:v.updateTime==null ? "-" :v.updateTime,
              iconcls: v.fileType == 1 ? 'icon_list_folder' : file_icon,
              checked:false,
            });
          });
          this.listLoading = false;
        } else {
          // this.$message.error(res.msg);
          this.listLoading = false;
        }
      });
    },
    selsChange(sels) {
      this.arrId = [];
      sels.forEach((val, key) => {
        this.arrId.push(val.fileId);
      });
      console.log(this.arrId);
    },
    cancelCollection() {
      if (this.arrId.length == 0) {
        return;
      };
      this.$confirm("确认取消收藏吗?", "提示", {
        // type: 'warning'
      }).then(() => {
        this.$http
          .post("/favorites/unCollection", {
            fileId: this.arrId
          })
          .then(res => {
            console.log(res);
            if (res.status == 200) {
              this.$message({
                message: "操作成功",
                type: "success"
              });
              this.getCollection();
            } else {
              this.$message.error("操作失败");
            }
          });
      });
    },
    getCollection() {
      this.addressList = [];
      this.collectionList = [];
      this.arrId = [];
      this.listLoading = true;
      // this.addressPrompt="我的收藏/" + this.addressList.join("/");
      this.$http.get("/favorites/getMyFavoritesList").then(res => {
        console.log(res);
        let { data, status } = res;
        if (status === 200 && data !== null) {
          this.hasCollect = true;
          // console.log(res);
          data.forEach((v, k) => {
            if (v.fileName == null) v.fileName = "未命名文件夹";
            let suffixTemp = v.fileName.split('.');
                let file_icon;
                if (suffixTemp.length > 1) {
                  suffixTemp = suffixTemp[suffixTemp.length - 1];
                  file_icon = 'icon_list_' + suffixTemp
                } else if (v.fileType == 0) {
                  suffixTemp = ''
                } else {
                  suffixTemp = null
                }
                // console.log(file_icon)
            this.collectionList.push({
              fileId: v.id,
              dirId: v.dirId,
              fileName: v.fileName,
              fileSize:v.fileSize == null ? "-" : this.$getFileSize(v.fileSize),
              creatTime: v.creatTime == null ? "-" : v.creatTime,
              suffix: suffixTemp,
              fileType: v.fileType,
              fileHash: v.fileHash,
              favoriteTime: v.favoriteTime,
              updateTime:v.updateTime==null ? "-":v.updateTime,
              iconcls: v.fileType == 1 ? 'icon_list_folder' : file_icon,
              checked:false,
            });
          });
          this.listLoading = false;
          // console.log(this.collectionList)
        } else {
          this.hasCollect = false;
          // this.message.error(res.msg);
          this.listLoading = false;
        }
      });
    },
    bigiconClicked(item) {
      console.log(item.checked);
      if(item.checked==false||item.checked==undefined){
        item.checked=true;
      }else{
        item.checked=false;
      }
      // item.checked = !item.checked;
      if(item.checked){
        this.arrId.push(item.fileId);
      }else{
          this.arrId.forEach((val,key)=>{
            if(val == item.fileId){
              this.arrId.splice(key,1);
            }
          })
      }
    },
  }
};
</script>
<style lang="scss">
@import "scss_vars";
#collection {
  position: relative;
  cursor:default;
   .el-button-group{
       margin-right: 10px;
        .el-button{
            padding:10px;
            width: 42px!important;
        }
        .focus{
            background: #549de8;
            border-color: #409EFF;
            color: #fff;
        }
    }
  .folder-box {
      display: flex;
      align-items: center;
      .file-name{
        flex: 1;
          &:hover {
              text-decoration: underline;
          }
      }
      .file-icon {
        background: url("/static/bigicon.png") no-repeat -196px 0px;
        display: inline-block;
        width: 28px;
        height: 29px;
        margin-right: 10px;
      }
      &.is-file {
        cursor: pointer;
      }

      .folder-box-options{
          display: none;
      }
    }
    .folder-box:hover .folder-box-options{
        display: block;
    }
    .el-header, .el-main {
      padding: 0;
    }
    .toolbar1 {
    background: #f6f6f6;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #f2f2f2;
    height: 54px;
    .el-row {
      display: flex;
      align-items: center;
      .back{
        margin-left: 20px;
      }
      .tit {
          line-height: 54px;
          padding-left:20px;
          border-left:1px solid #eee;
          margin-left: 20px;
        i:hover{
           text-decoration: underline;
           cursor: pointer;
         }
        .current{
          color:#2b2b2b;
          font-weight: 900;
        }
      }
      .el-button {
        padding: 10px;
        width: 82px;
      }
      .el-button:hover{
        background: $aside-bg;
         color: $white;
      }
      .activeList {
        color: $white;
         background: $aside-bg;
       }
        .refresh{
            margin-right: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            width: 42px;
            height: 36px;
        }
      .list{
        margin:0;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 42px;
        height: 36px;
      }
      .menu{
        margin-right: 5px;
        margin-left: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 42px;
        height: 36px;
      }
    }
  }
    .el-main {
      .toolbar {
        padding: 9px 0 9px 20px;
        height: 36px;
        border-bottom: 1px solid $black-bg;
        margin:0;
        i{
          color: $white;
        }
      }
      .el-button {
        height: 36px;
        font-size: 14px;
        font-family: SourceHanSansCN-Regular;
        font-weight: 400;
        color: rgba(102, 102, 102, 1);
      }
      .bt1 {
        background: rgba(84, 157, 232, 1);
        color: $white;
      }
      .bt1:focus {
        background: rgba(84, 157, 232, 0.8);
      }
      .bt1:hover {
        background: rgba(84, 157, 232, 0.8);
      }
      .btlast {
        margin-right: 10px;
      }
      .big-show{
        .top{
            height: 72px;
            border-bottom:1px solid #eee;
            padding-left: 40px;
            display: flex;
            align-items: center;
            img{
                margin-right: 31px;
            }
        }
        .file-icon {
        background: url("/static/bigicon.png") no-repeat -196px 0px;
        display: inline-block;
        width: 28px;
        height: 29px;
        margin-right: 10px;
      }
      .bigIcon:hover{
        border:1px solid #549DE8;
        img{
          display: inline-block;
        }
        .hovershow{
        display: inline-block;
      }
      }
        .bigIcon{
          line-height: 54px;
          box-sizing: border-box;
          width:256px;
          height:54px;
          border:1px solid rgba(238,238,238,1);
          float: left;
          margin-left:20px;
          margin-top:20px;
          display: flex;
      align-items: center;
      position: relative;
      .hovershow{
        display: none;
      }
      img{
        position:absolute;
        top: 0;
        right: 0;
      }
      .file-name{
        flex: 1;
      }
      &:hover {
        text-decoration: underline;
        cursor: pointer;
      }
          .icon{
            margin-left:20px;
          }
        }
        .checked{
        border:1px solid #549DE8;
        img{
          display: inline-block;
        }
        .hovershow{
        display: inline-block;
      }
      .file-name{
        text-decoration: underline;
        cursor: pointer;
      }
      }
      }
    }
}
</style>

